package widget;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by LLAP on 2017/12/13.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class TRadioGroup extends TComponent {
    private LinkedList<JRadioButton> radioButtons;
    private ButtonGroup group;
    public TRadioGroup(String name, Object[] options, String comment, boolean required) {
        super(
                name,
                new JPanel(new GridLayout(1, options.length, 5, 5)),
                comment,
                required
        );
        group = new ButtonGroup();
        radioButtons = new LinkedList<>();

        for (Object i : options) {
            JRadioButton r = new JRadioButton(i.toString());
            radioButtons.add(r);
            group.add(r);
            this.field.add(r);
        }
    }
    public TRadioGroup(String name, Object[] options, boolean required) {
        this(name, options, name, required);
    }
    public TRadioGroup(String name, Object[] options, String comment) {
        this(name, options, comment, false);
    }
    public TRadioGroup(String name, Object[] options) {
        this(name, options, name);
    }

    @Override
    public void clear() {
        for (JRadioButton i : radioButtons) {
            i.setSelected(false);
        }
    }

    @Override
    public HashMap<String, Object> getData() {
        HashMap<String, Object> ret = new HashMap<>();
        boolean flag = false;
        for (JRadioButton r : radioButtons) {
            if (r.isSelected()) {
                flag = true;
                ret.put(name, r.getText());
                break;
            }
        }
        if (!flag) {
            if (required) throw new IllegalArgumentException(this.comment + "未选中任何项目");
            else ret.put(name, "");
        }
        return ret;
    }
}